package com.service;

import com.dao.UserDao;
import com.dao.UserDaoImp.UserDaoImpl;
import com.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class UserService {

    private UserDao userDao;
    private SqlSession sqlSession;
    public UserService() {
        init();
    }
    //验证
    public boolean login(User user){
        User loginUser = userDao.queryUserByUserName(user.getUsername());
        if(loginUser != null && loginUser.getPassword()!=null){
            if(loginUser.getPassword().equals(user.getPassword())){
                return true;
            };
        }
        return false;
    }

    public List<User> getUserAll(){
        return userDao.queryUserAll();
    }

    //删除
    public void delete(String username){
        userDao.deleteUser(username);
    }

    //注册
    public void addUser(User user){
        userDao.insertUser(user);
    }

    //初始化
    public  void init(){
        try{
            String resource = "mybatis-config.xml";
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession();
            userDao = new UserDaoImpl(sqlSession);
        }catch (Exception ex){}
    }
}
